import { Management } from "d8d-manage-react";
import { useState } from "react";
import { Card, List, Modal, Form, Input, message } from "antd";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { usersApi } from "../../api/users.ts";
import type { AdminUsersData } from "../../../../server/shared/types.ts";

interface User {
  id: number;
  username: string;
}

interface UserFormData {
  username: string;
  password: string;
}

export default function Users() {
  const [searchValue, setSearchValue] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm<UserFormData>();
  const queryClient = useQueryClient();

  const { data, isLoading, refetch } = useQuery<AdminUsersData>({
    queryKey: ["users"],
    queryFn: usersApi.getUsers,
  });

  const createMutation = useMutation({
    mutationFn: usersApi.createUser,
    onSuccess: () => {
      message.success("用户创建成功");
      queryClient.invalidateQueries({ queryKey: ["users"] });
      setIsModalOpen(false);
      form.resetFields();
    },
    onError: (error) => {
      message.error(error instanceof Error ? error.message : "创建失败");
    }
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<UserFormData> }) =>
      usersApi.updateUser(id, data),
    onSuccess: () => {
      message.success("用户更新成功");
      queryClient.invalidateQueries({ queryKey: ["users"] });
      setIsModalOpen(false);
      setEditingUser(null);
      form.resetFields();
    },
    onError: (error) => {
      message.error(error instanceof Error ? error.message : "更新失败");
    }
  });

  const deleteMutation = useMutation({
    mutationFn: usersApi.deleteUser,
    onSuccess: () => {
      message.success("用户删除成功");
      queryClient.invalidateQueries({ queryKey: ["users"] });
    },
    onError: (error) => {
      message.error(error instanceof Error ? error.message : "删除失败");
    }
  });

  const users = data?.users ?? [];
  const filteredUsers = users.filter((user: User) =>
    user.username.toLowerCase().includes(searchValue.toLowerCase())
  );

  const handleSubmit = async (values: UserFormData) => {
    if (editingUser) {
      await updateMutation.mutateAsync({
        id: editingUser.id,
        data: values
      });
    } else {
      await createMutation.mutateAsync(values);
    }
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue({ username: user.username, password: '' });
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这个用户吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: () => deleteMutation.mutateAsync(id)
    });
  };

  return (
    <>
      <Management<User>
        title="用户管理"
        items={filteredUsers}
        loading={isLoading}
        pagination={{
          current: 1,
          pageSize: 10,
          total: filteredUsers.length,
        }}
        hasMore={false}
        onSearch={(value: string) => setSearchValue(value)}
        onRefresh={() => refetch()}
        onAdd={() => {
          setEditingUser(null);
          form.resetFields();
          setIsModalOpen(true);
        }}
        onPageChange={(page: number) => console.log("页码变化:", page)}
        loadMore={() => console.log("加载更多")}
        renderItem={(item: User) => (
          <List.Item 
            key={item.id}
            actions={[
              <a key="edit" onClick={() => handleEdit(item)}>编辑</a>,
              <a key="delete" onClick={() => handleDelete(item.id)} className="text-red-500">删除</a>
            ]}
          >
            <Card key={item.id} className="mb-4 w-full">
              <p>ID: {item.id}</p>
              <p>用户名: {item.username}</p>
            </Card>
          </List.Item>
        )}
        searchPlaceholder="搜索用户"
        addButtonText="添加用户"
      />

      <Modal
        title={editingUser ? "编辑用户" : "添加用户"}
        open={isModalOpen}
        onOk={() => form.submit()}
        onCancel={() => {
          setIsModalOpen(false);
          setEditingUser(null);
          form.resetFields();
        }}
        confirmLoading={createMutation.isPending || updateMutation.isPending}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: !editingUser, message: "请输入密码" },
              editingUser ? {} : { min: 6, message: "密码至少6位" }
            ]}
          >
            <Input.Password placeholder={editingUser ? "不修改请留空" : "请输入密码"} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
